package com.schooldate.model.action;

import com.gexin.rp.sdk.base.ITemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.openFire.entity.User;
import com.openFire.util.Blowfish;
import com.schooldate.base.BaseAction;
import com.schooldate.model.entity.Department;
import com.schooldate.model.entity.School;
import com.schooldate.model.entity.UserInfo;
import com.schooldate.util.CreateCode;
import com.schooldate.util.SimpleJsonFilter;
import com.schooldate.util.push.PushUtils;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.util.Set;

/**
 * Created by etund on 2015/3/13 0013.
 */
@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class UserInfoAction extends BaseAction<UserInfo>{

    private String reciUserId;
    private String sendUserId;
    private Integer sendNum = 1;
    //学校名字
    private String schoolId;
//   学院名字
    private String departmentId;

    private String verificationCode;


    public void autoRefalsh() throws Exception{
        System.out.println("quartz任务调度执行");
        userInfos = this.userInfoService.getByLoginInfo();
        for (UserInfo userInfo:userInfos){
            userInfo.setIsLoginToday(false);
            userInfo.setFlowerSendLeft(10L);
            this.userInfoService.update(userInfo);
        }
    }

    /**
     * 送花
     * @return
     * @throws Exception
     */
    public void sendFlower() throws Exception{
        UserInfo reciUser = this.userInfoService.getById(Long.parseLong(reciUserId));
        UserInfo sendUser = this.userInfoService.getById(Long.parseLong(sendUserId));
        if (sendUser.getFlowerSendLeft() >= sendNum){
            sendUser.setFlowerSendLeft(sendUser.getFlowerSendLeft() - sendNum);
            reciUser.setReciFlower(reciUser.getReciFlower() + sendNum);
            this.userInfoService.update(sendUser);
            this.userInfoService.update(reciUser);
            PushUtils.pushToSingle(reciUser.getDevicetoken(),"有人送花给你啦！快来看看吧!");
            object.put("code",1);
            result = JSON.toJSONString(object);
            renderJson(result);
        }else{
            object.put("code",0);
            result = JSON.toJSONString(object);
            renderJson(result);
        }
    }

    /**
     *申请修改密码
     * @return
     */
    public void applyChangePassword() throws Exception{
//        如果是忘了密码
        if (verificationCode != null){
            String serviceCode = (String) this.session.get("VerificationCode");
            if (verificationCode.equals(serviceCode)){
                object.put("code",1);
                result = JSON.toJSONString(object);
                renderJson(result);
            }
        }
        if (model.getEmail()!=null&& model.getPassword()!=null){
            UserInfo userInfo = this.userInfoService.getByEmailAndPassword(model.getEmail(),model.getPassword());
            if (userInfo != null){
                object.put("code",1);
                result = JSON.toJSONString(object);
                renderJson(result);
            }
        }
        object.put("code",0);
        result = JSON.toJSONString(object);
        renderJson(result);
    }


    /**
     * 修改密码
     */
    public void changePassword()  throws Exception{
        this.userInfoService.update(model);
        object.put("code",0);
        result = JSON.toJSONString(object);
        renderJson(result);
    }


    /**
     * 忘记密码
     * @return
     * @throws Exception
     */
    public void forgetPassword() throws  Exception{
        System.out.println(model.getEmail()+"====================");
        if (model.getEmail()==null||"".equals(model.getEmail().trim())){
            object.put("code",0);
            result = JSON.toJSONString(object);
            renderJson(result);
            return;
        }
        UserInfo userInfo = this.userInfoService.getByEmail(model.getEmail());
        if (userInfo==null){
            object.put("code",0);
            result = JSON.toJSONString(object);
            renderJson(result);
            return;
        }
         verificationCode = CreateCode.getSecurityCode();
//        发邮件
        sendEmail(verificationCode,model.getEmail());
        object.put("verificationCode",verificationCode);
        object.put("code",1);
        result = JSON.toJSONString(object);

        renderJson(result);
    }


    /**
     * 登录
     * @return
     * @throws Exception
     */
        public void login() throws Exception {
        UserInfo userInfo =  this.userInfoService.getByEmailAndPassword(model.getEmail(), model.getPassword());
        if (userInfo!= null){
//            已经登陆
            userInfo.setIsLoginToday(true);
//            返回json数据给移动端
            SimpleJsonFilter filter = new SimpleJsonFilter("userInfo");
            object.put("code", 1);
            userInfo.setUserId(userInfo.getId());
            this.userInfoService.update(userInfo);
            object.put("userInfo", userInfo);
           result =  JSON.toJSONString(object,filter, SerializerFeature.DisableCircularReferenceDetect );
            renderJson(result);
        }
        object.put("code", 0);
        result =  JSON.toJSONString(object);
    }

    /**
     * 注册
     * @return
     */
    public void registerUser() throws Exception{
        School school = this.schoolService.getBySchoolName(schoolId);
        if (school==null){
            object.put("code",0);
            result = JSON.toJSONString(object);
            renderJson(result);
            return;
        }
        model.setSchool(school);
        Department department = this.departmentService.getBySchoolIdAndName(school.getSid(),departmentId);
        model.setDepartment(department);

        //        上传头像文件
        if (file!=null&&file.length>0){
            uploadFileReturnPath("userImages");
            System.out.println(fileFullPath+"=========messageBoardImagePath==================");
            if (model.getImagesPath()!=null){
                model.setImagesPath(model.getImagesPath()+","+fileFullPath);
            }else {
                model.setImagesPath(fileFullPath);
            }
            model.setHeadImagePath(fileFullPath);
        }

//        保存userId
        this.userInfoService.save(model);
        model.setUserId(model.getId());
        this.userInfoService.update(model);

//        保存openFire用户
        User user = new User();
        user.setUsername(model.getId().toString());
        user.setCreationDate("00"+System.currentTimeMillis());
        user.setModificationDate("00"+System.currentTimeMillis());
        user.setEncryptedPassword(_encoder.encryptString(model.getPassword()));
        this.userService.save(user);

        object.put("code", 0);
        result = JSON.toJSONString(object);
        renderJson(result);
    }

    /**
     * 点击我的
     * @throws Exception
     */
    public void clickMe() throws Exception{
        UserInfo userInfo = this.userInfoService.getById(model.getId());
        SimpleJsonFilter filter = new SimpleJsonFilter("clickMe.do");
        object.put("userInfo",userInfo);
        object.put("code",1);
        result = JSON.toJSONString(object);
        renderJson(result);
    }




    public String getVerificationCode() {
        return verificationCode;
    }

    public void setVerificationCode(String verificationCode) {
        this.verificationCode = verificationCode;
    }

    public String getReciUserId() {
        return reciUserId;
    }

    public void setReciUserId(String reciUserId) {
        this.reciUserId = reciUserId;
    }

    public Integer getSendNum() {
        return sendNum;
    }

    public void setSendNum(Integer sendNum) {
        this.sendNum = sendNum;
    }

    public String getSchoolId() {
        return schoolId;
    }

    public void setSchoolId(String schoolId) {
        this.schoolId = schoolId;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public String getSendUserId() {
        return sendUserId;
    }

    public void setSendUserId(String sendUserId) {
        this.sendUserId = sendUserId;
    }
}
